
var MY_PRESCRIPTION_SUPERVISION = (function () {

    var mainColor = 'rgb(2, 251, 255)';

    //获取页面统计信息
    function loadChartInfo() {
        $.ajax({
            type: "POST",
            url: "invs_home_page.do/load_chart_info",
            data: {id : '411', datePatten : 1},
            success: function(data) {
                WeKnow.closeLoading();
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                if (data.errorcode == 0) {
                    var chartInfo = data.chartInfo;

                    setSelectpickerOptions(chartInfo.searchTypes);
                    //监管处方数量
                    drawPrescriptionSupervisionTotal(chartInfo.allPresCnt);
                    //违规机构
                    drawIllegalInstitutionsProportion(chartInfo.errorInstCnt, chartInfo.allInstCnt);
                    //违规处方
                    drawIllegalPrescriptionProportion(chartInfo.errorPresCnt, chartInfo.allPresCnt);
                    //处方违规数趋势
                    drawTrendLine(chartInfo.violateTimeLine);
                    //处方违规机构等级
                    drawLevelBar(chartInfo.presViolateInstitutionByLevel);
                    //处方违规机构街道分布
                    drawDistributionPolar(chartInfo.prescriptionViolation);
                    //处方违规类型
                    drawTypeBar(chartInfo.presDailyByType);
                    //绘制违规机构行业性质
                    drawIndustryPie(chartInfo.presViolateInstitutionByType);
                    //绘制违规机构经济性质
                    drawEconomicPie(chartInfo.presViolateInstitutionByAttr);
                    //地图标注点
                    //MY_MAP.loadMarker(chartInfo.presViolateInstitutionList);
                    MY_MAP.loadMarkerClick(chartInfo.presViolateInstitutionList);
                } else if (data.errorcode == -1 ){
                    WeKnow.errorMsg( data.errMsg );
                } else {
                    WeKnow.systemMsg('查询失败，请重新登录');
                }
            }
        });
    }

    //监管处方数量
    function drawPrescriptionSupervisionTotal(data) {
        if(data == null || data.length == 0) {
            return;
        }

        //清空
        document.getElementById("prescriptionSupervisionTotal").innerHTML = "";

        var numbers =  data.toString();
        var length = numbers.length;

        for(var i=0; i < 4-length; i++) {
            $("#prescriptionSupervisionTotal").append(
                "<span class='middleAboveNumFont'>" + 0 + "</span>"
            );
        }

        for(var i=0; i < length; i++) {
            $("#prescriptionSupervisionTotal").append(
                "<span class='middleAboveNumFont'>" + numbers[i] + "</span>"
            );
        }
    }

    //违规机构
    function drawIllegalInstitutionsProportion(illegal, all) {
        if(illegal == null || illegal.length == 0) {
            illegal = 0;
        }

        if(all == null || all.length == 0) {
            all = 0;
        }

        //清空
        document.getElementById("illegalInstitutionsProportion").innerHTML = "";

        var percent = all > 0 ? Math.round(illegal  * 100 / all) : 0;

        $("#illegalInstitutionsProportion").append(
            "<span>" + illegal + "家</span>"
            + "<span>" + percent +"%</span>"
        );
    }

    //违规处方
    function drawIllegalPrescriptionProportion(illegal, all) {
        if(illegal == null || illegal.length == 0) {
            illegal = 0;
        }

        if(all == null || all.length == 0) {
            all = 0;
        }

        //清空
        document.getElementById("illegalPrescriptionProportion").innerHTML = "";

        var percent = all > 0 ? Math.round(illegal  * 100 / all) : 0;

        $("#illegalPrescriptionProportion").append(
            "<span>" + illegal + "份</span>"
            + "<span>" + percent +"%</span>"
        );
    }

    //处方违规数趋势
    function drawTrendLine(data) {
        if (data.length == 0) {
            return;
        } else {
            var nameData = [];
            var valueData = [];
            var year = (new Date()).getFullYear();
            var cWeek = data.length > 0 ? data[0].name : '';
            for(var i=data.length; i > 0; i--){
                var temp = cWeek >= data[i-1].name ? year : year-1;
                data[i-1].name = temp.toString().substring(2,4) + '年' + data[i-1].name + '周';
                nameData.push(data[i-1].name);
                valueData.push(data[i-1]);
            }
        }
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.querySelector("#trendLine"));
        // 2. 指定配置和数据
        option = {
            tooltip: {
                trigger: "axis",
                axisPointer: {
                    lineStyle: {
                        color: mainColor
                    }
                }
            },
            grid: {
                left: fontChart(0.375),
                top: fontChart(0.3125),
                right: fontChart(0.25),
                bottom: fontChart(0.1875),
                containLabel: true
            },
            xAxis: [
                {
                    type: "category",
                    boundaryGap: false,
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: false
                    },
                    data: nameData,
                    axisLabel: {
                        margin: fontChart(0.2),
                        interval:0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
                        rotate: 30,   //调整数值改变倾斜的幅度（范围-90到90）
                        textStyle: {
                            color: mainColor,
                            fontSize: fontChart(0.15)
                        }
                    },
                    grid: {
                        left: '0%',
                        bottom:'90%'
                    },
                },
                {
                    axisPointer: { show: false },
                    axisLine: { show: false },
                    position: "bottom",
                    offset: 20
                }
            ],
            yAxis: [
                {
                    type: "value",
                    min: 0,
                    minInterval: 1,
                    axisTick: { show: false },
                    axisLine: {
                        show: false
                    },
                    axisLabel: {
                        textStyle: {
                            color: mainColor,
                            fontSize: fontChart(0.15)
                        }
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            series: [
                {
                    name: "",
                    type: "line",
                    smooth: true,
                    symbol: "circle",
                    symbolSize: 5,
                    showSymbol: false,
                    lineStyle: {
                        normal: {
                            color: mainColor,
                            width: 2
                        }
                    },
                    areaStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: mainColor
                            }, {
                                offset: 1,
                                color: 'rgba(88,255,225,0.1)'
                            }]),
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: mainColor,
                            borderColor: "rgba(221, 220, 107, .1)",
                            borderWidth: 12
                        }
                    },
                    data: valueData
                }
            ]
        };
        // 3. 把配置和数据给实例对象
        myChart.setOption(option);
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    };

    //处方违规机构等级
    function drawLevelBar(data) {
        if (data.length == 0) {
            return;
        } else {
            var nameData = [];
            var valueData = [];
            for(i=0;i<data.length;i++){
                nameData.push(data[i].name);
                valueData.push(data[i]);
            }
        }
        // 1. 实例化对象
        var myChart = echarts.init(document.querySelector("#levelBar"));
        // 2. 指定配置项和数据
        option = {
            title: {
                subtext: '机构数',
                subtextStyle: {
                    color: mainColor,
                }
            },
            grid:{
                x: 40,
                y: 60,
                x2: 15,
                y2: 20,
            },
            tooltip : {
                trigger: 'axis'
            },
            calculable : true,
            xAxis : [
                {
                    type : 'category',
                    data : nameData,
                    axisLine: {
                        lineStyle: {
                            color: mainColor
                        }
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            yAxis : [
                {
                    type : 'value',
                    min: 0,
                    minInterval : 1,
                    axisLine: {
                        lineStyle: {
                            color: mainColor
                        }
                    },
                    splitLine: {
                        show: false
                    },
                }
            ],
            series : [
                {
                    name:'机构数',
                    type:'bar',
                    data:valueData,
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                offset: 0,
                                color: mainColor
                            }, {
                                offset: 1,
                                color: '#195bff'
                            }]),
                        }
                    },
                    barWidth : 40
                }
            ]
        };

        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function() {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    };

    //处方违规机构行业性质
    function drawIndustryPie(data) {
        if (data.length == 0) {
            return;
        } else {
            var nameData = [];
            var valueData = [];
            for(i=0;i<data.length;i++){
                if(data[i].value > 0) {
                    nameData.push(data[i].name);
                    valueData.push(data[i]);
                }
            }
        }
        // 1. 实例化对象
        var myChart = echarts.init(document.querySelector("#industryPie"));
        // 2. 指定配置项和数据
        option = {
            tooltip : {
                trigger: 'item',
                formatter: "{b}<br/>{c} ({d}%)"
            },
            color: [
                "#d7cd3a",
                "#8c0d94",
                "#ce6366",
                "#217eff",
                mainColor,
            ],
            series : [
                {
                    name:'',
                    type:'pie',
                    center: ["50%", "50%"],
                    radius : ['50%', '80%'],
                    labelLine : {
                        show : true,
                        normal:{
                            length: 15,  // 改变标示线的长度
                            lineStyle: {
                                color: mainColor  // 改变标示线的颜色
                            }
                        },
                    },
                    itemStyle : {
                        normal : {
                            label : {
                                formatter: "{b}\n{c} ({d}%)",
                                textStyle: {
                                    color: mainColor  // 改变标示文字的颜色
                                },
                                position: 'inner',
                                show : false
                            },
                        },
                        emphasis : {
                            label : {
                                show : false,
                                position : 'center',
                                textStyle : {
                                    fontSize : fontChart(0.15)
                                }
                            }
                        }
                    },
                    data:valueData
                }
            ]
        };
        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function() {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    };

    //处方违规机构经济性质
    function drawEconomicPie(data) {

        var valueData = [
            {'name':'公立', 'value':0},{'name':'民营', 'value':0}
        ];

        var nameData = [];
        for(var i=0; i < valueData.length; i++){
            nameData.push(valueData[i].name);
        }

        if (data.publicCnt != undefined) {
            valueData[0].value = data.publicCnt;
        }

        if (data.privateCnt != undefined) {
            valueData[1].value = data.privateCnt;
        }

        // 1. 实例化对象
        var myChart = echarts.init(document.querySelector("#economicPie"));
        // 2. 指定配置项和数据
        option = {
            tooltip : {
                trigger: 'item',
                formatter: "{b}<br/>{c} ({d}%)"
            },
            color: [
                mainColor,
                "#217eff",
            ],
            series : [
                {
                    name:'',
                    type:'pie',
                    center: ["50%", "50%"],
                    radius : ['50%', '80%'],
                    labelLine : {
                        show : true,
                        normal:{
                            length: 20,  // 改变标示线的长度
                            lineStyle: {
                                color: mainColor  // 改变标示线的颜色
                            }
                        },
                    },
                    itemStyle : {
                        normal : {
                            label : {
                                show : true,
                                formatter: "{b}\n{c} ({d}%)",
                                textStyle: {
                                    color: mainColor  // 改变标示文字的颜色
                                }
                            },
                            labelLine : {
                                show : true
                            }
                        },
                        emphasis : {
                            label : {
                                show : false,
                                position : 'center',
                                textStyle : {
                                    fontSize : fontChart(0.15)
                                }
                            }
                        }
                    },
                    data:valueData
                }
            ]
        };
        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function() {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    };

    //处方违规机构街道分布
    function drawDistributionPolar(data) {
        if (data.length == 0) {
            return;
        } else {
            var nameData = [];
            for(i=0;i<data.length;i++){
                nameData.push(data[i].name);
            }
        }
        // 1. 实例化对象
        var myChart = echarts.init(document.querySelector("#distributionPolar"));
        // 2. 指定配置项和数据
        option = {
            tooltip: {
                trigger: 'item',
            },
            angleAxis: {//极坐标系的角度轴
                type: 'category',
                startAngle: 90,
                splitNumber: 12, //坐标轴分割段数
                minInterval: 30,
                maxInterval: 30,
                interval: 30,
                axisLine: { //坐标轴轴线设置
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.6)',
                    }
                },
                axisTick: { //坐标轴刻度设置
                    show: true,
                },
                splitLine: { //分割线设置
                    show: false,
                },
                axisLabel: { //刻度标签设置
                    textStyle: {
                        color: mainColor
                    }
                },
                data: nameData
            },
            radiusAxis: {
                min: 0,
                minInterval: 1,
                axisLine: { //坐标轴轴线设置
                    show: true,
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.6)'
                    }
                },
                axisTick: { //坐标轴刻度设置
                    show: true
                },
                axisLabel: { //刻度标签设置
                    margin: 5, //刻度与坐标轴之间的距离
                    textStyle: {
                        color: mainColor
                    }
                }
            },
            polar: {
                center: ['50%', '50%']
            },
            series: [{
                type: 'bar',
                data: data,
                coordinateSystem: 'polar',
                lineStyle: {
                    normal: {
                        color: 'rgba(255, 255, 255, 0.9)'
                    }
                },
                itemStyle: {
                    normal: {
                        color: mainColor
                    }
                },
                animationDuration: 2000
            }],
        };

        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function() {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    }

    //处方违规类型
    function drawTypeBar(data) {
        var valueData = [
            {name:"医疗机构超范围诊疗", value:0},{name:"医师超范围开具处方", value:0},{name:"多个执业地点同时开具处方", value:0},
            {name:"无处方权开具处方", value:0},{name:"执业助理医师开具处方", value:0},{name:"未经批准开具精麻药品", value:0},
            {name:"未经培训合格开具抗菌药物", value:0}, {name:"越级使用抗菌药物", value:0},{name:"未经药师调剂药品", value:0},
            {name:"不合理用药", value:0},{name:"非执业点开处方", value:0},
        ];

        if (data != undefined && data != null && data.length > 0) {
            for (var i=0; i < data.length; i++) {
                switch (data[i].type) {
                    case "810001":
                        valueData[0].value = data[i].value;
                        break;
                    case "810002":
                        valueData[1].value = data[i].value;
                        break;
                    case "810003":
                        valueData[2].value = data[i].value;
                        break;
                    case "820001":
                        valueData[3].value = data[i].value;
                        break;
                    case "820002":
                        valueData[4].value = data[i].value;
                        break;
                    case "820003":
                        valueData[5].value = data[i].value;
                        break;
                    case "820004":
                        valueData[6].value = data[i].value;
                        break;
                    case "820005":
                        valueData[7].value = data[i].value;
                        break;
                    case "830001":
                        valueData[8].value = data[i].value;
                        break;
                    case "840001"://包含所有84开头
                        valueData[9].value = data[i].value;
                        break;
                    case "850001":
                        valueData[10].value = data[i].value;
                        break;
                }
            }
            valueData.sort(sortValue);
        }

        var nameData = [];
        for (var j=0; j < valueData.length; j++) {
            nameData.push(valueData[j].name);
        }

        // 1. 实例化对象
        var myChart = echarts.init(document.querySelector("#typeBar"));
        // 2. 指定配置项和数据
        option = {
            color: [mainColor],
            xAxis : [
                {
                    type : 'value',
                    show: false,
                    axisLine: {
                        show: false
                    },
                    axisTick:{
                        show: false
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            yAxis : [
                {
                    min: 0,
                    minInterval: 1,
                    type : 'category',
                    data : nameData,
                    axisLine:{
                        show: false,
                        lineStyle:{
                            color: 'white',
                            fontSize:fontChart(0.17)
                        }
                    },
                    axisTick:{
                        "show":false
                    },
                    splitLine: {
                        "show": false
                    }
                }
            ],
            grid: {
                left: '1%',
                right: '5%',
                bottom: '5%',
                top: '7%',
                containLabel: true
            },
            series : [
                {
                    type:'bar',
                    barMinHeight: 1,
                    barWidth: 15,
                    itemStyle : {
                        normal: {
                            label : {
                                show: true,
                                position: 'right',
                                // color: 'white'
                            },
                        }
                    },
                    data:valueData
                }
            ]
        };
        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function() {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    };

    function sortValue(a, b) {
        return a.value - b.value;
    }

    //自适应字体大小
    function fontChart(res) {
        //获取到屏幕的宽度
        var clientWidth =
            window.innerWidth ||
            document.documentElement.clientWidth ||
            document.body.clientWidth;
        if (!clientWidth) return; //报错拦截：
        var fontSize = 80 * (clientWidth / screen.width);
        return res * fontSize;
    }

    function setSelectpickerOptions(data) {
        setOptionsCommon('street', data.district);
        setOptionsCommon('industry', data.industry);
        setOptionsCommon('level', data.level);
        setOptionsCommon('economic', data.economic);
        setOptionsCommon('ownership', data.ownership);
        $('.selectpicker').selectpicker('refresh');
    }

    function setOptionsCommon(name, data) {
        if (data == undefined) {
            return;
        }

        if (name == 'economic') {
            document.getElementById("economicOption0").textContent = "公立 (" + data.publicCnt + ")";
            document.getElementById("economicOption1").textContent = "民营 (" + data.privateCnt + ")";
        } else {
            var ele = $("#"+name + "Select");
            for (var i=0; i < data.length; i++) {
                var id = name + 'Option' + data[i].id;
                var element = document.getElementById(id);
                if (element) {
                    element.textContent =  data[i].name + " (" + data[i].value + ")";
                } else {
                    ele.append("<option value=" + data[i].id + " id=" + id + ">" + data[i].name + " (" + data[i].value + ")</option>");
                }
            }
        }
    }

    function getParamsSearch(searchKey, currentPage, limit) {
        var params = {};

        params.searchKey = searchKey;
        params.currentPage = currentPage;
        params.limit = limit;
        params.street = $('#streetSelect').find("option:selected").val();
        params.industry = $('#industrySelect').find("option:selected").val();
        params.economic = $('#economicSelect').find("option:selected").val();
        params.level = $('#levelSelect').find("option:selected").val();
        params.ownership = $('#ownershipSelect').find("option:selected").val();

        return params;
    }

    function searchLoad(target, searchKey, currentPage) {
        var limit = 10;
        var $that = target;
        var params = getParamsSearch(searchKey, currentPage, limit);
        $.ajax({
            type: "POST",
            url: "invs_home_page.do/dispaly_search_login",
            data: params,
            success: function(data) {
                WeKnow.closeLoading();
                if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

                if (data.errorcode == 0) {
                    var institutionList = data.institutionList;
                    var total = data.total;
                    $('#searchList').empty();
                    if (institutionList == null || institutionList.length == 0 ) {
                        //
                    } else {

                        $(institutionList).each(function (idx, g) {
                            $((function () {
                                var e = '';
                                e += '<tr class="search-tr">';
                                e += '<td class="search-td">' + g.name + '</td>';
                                e += '<td style="display:none">' + g.id + '</td>';
                                e += '</tr>';
                                return e;
                            })()).appendTo($('#searchList')).on('click', function () {
                                $('input#insitutionNameSearch').val(g.name);
                                $('button#institutionDetails').attr("data-institutionname", g.name);
                                $('button#institutionDetails').attr("data-institutionid", g.id);

                                //判断状态是否为全屏
                                var screenState = $("#full_scr").is(":hidden") ? 'fullScreen' : 'exitFullScreen';
                                WeKnow.submit(
                                    'invs_institution_details.do',
                                    {
                                        screenState: screenState,
                                        pageId: "prescriptionSupervision",
                                        institutionName: g.name,
                                        institutionId: g.id,
                                    }
                                );
                            });
                        });
                    }

                    // $('.selectpicker').selectpicker('refresh');

                    if (total > limit) {
                        $('div.layui-table-page').show();
                    } else {
                        $('div.layui-table-page').hide();
                    }

                    layui.use('laypage', function(){
                        var laypage = layui.laypage;
                        //执行一个laypage实例
                        laypage.render({
                            elem: 'searchPagination',
                            count: total,
                            limit: limit,
                            curr: currentPage,
                            // theme: 'rgb(46,76,255)',
                            jump: function (obj, first) { //obj为当前页的属性和方法，第一次加载first为true
                                //非首次加载 do something
                                if (!first) {
                                    //清空以前加载的数据
                                    $('#searchList').empty();
                                    //调用加载函数加载数据
                                    MY_PRESCRIPTION_SUPERVISION.searchLoad($that, searchKey, obj.curr);
                                }
                            }
                        });
                    });

                } else if (data.errorcode == -1 ) {
                    WeKnow.errorMsg( data.errMsg );
                } else {
                    WeKnow.systemMsg('查询失败，请重新登录');
                }
            }
        });
    }

    return {
        loadChartInfo:loadChartInfo,
        searchLoad:searchLoad,
    }
})();

$(document).ready(function() {

    MY_MAP.initMap("prescription_supervision");
    MY_PRESCRIPTION_SUPERVISION.loadChartInfo();
    setInterval(function(){ MY_PRESCRIPTION_SUPERVISION.loadChartInfo(); }, 5000);

    $('#economicSelect, #ownershipSelect, #levelSelect').selectpicker({
        width: MY_HOME_PAGE_COMMON.fontChart(1.5)
    });

    $('#industrySelect, #streetSelect').selectpicker({
        width: MY_HOME_PAGE_COMMON.fontChart(2)
    });

    $('.selectpicker').on('change',function(){
        $("input#insitutionNameSearch").trigger("click");
    });

    $("#institutionDetails").on('click',function () {
        $("input#insitutionNameSearch").trigger("click");
    });

    var autoSearch;
    $('input#insitutionNameSearch').on('input click', function () {

        if (document.getElementById("searchMenu").style.display == 'none') {
            document.getElementById("searchMenu").style.display = 'inline';
        }

        if ($("#searchMenu").is(":hidden")) {
            $("#searchMenu").show();
            $(document).one("click",function () {
                $("#searchMenu").hide();
            });
            e.stopPropagation();
        }

        if (autoSearch) clearTimeout(autoSearch);

        var $that = $(this);
        var searchKey = $.trim($that.val());
        // if (searchKey.length) {
        autoSearch = setTimeout(MY_PRESCRIPTION_SUPERVISION.searchLoad($that, searchKey, 1), 500);
        // }
    });

    $("#container, div[class$='Chart']").on('click', function(e) {
        if (document.getElementById("searchMenu").style.display == 'inline') {
            document.getElementById("searchMenu").style.display = 'none';
        }
    });
});

